package com.tanhua.manage.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.manage.pojo.User;
import com.tanhua.manage.pojo.UserInfo;
import com.tanhua.manage.vo.ManageUserInfoVo;
import com.tanhua.manage.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.util.*;

import java.util.stream.Collectors;

@Service
public class ManageUsersService {

    //冻结列表
    private String FREEZ_KEY_TIME="FREEZ_KEY_TIME_";

    private String FREEZ_KEY_RANGE="FREEZ_KEY_RANGE_";

    @Autowired
    private UserServcie userServcie;


    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //查询用户列表
    public PageResult queryManageUsersList(Integer page, Integer pageSize, Integer id, String nickname, String city, String token) {
        //User = UserThreald.getUser();TODO

      //如果有关键字查询的话,就收集关键字查询的信息
        QueryWrapper<UserInfo> queryWrapper =new QueryWrapper();
        if (id!=null){
            queryWrapper.eq("user_id",id);
        }
        if (StringUtils.isNotEmpty(nickname)){
            queryWrapper.like("nike_name",nickname);
        }
        if (StringUtils.isNotEmpty(city)){
            queryWrapper.like("city",city);
        }

        PageResult pageResult = getPageResult(page, pageSize, queryWrapper);

        return pageResult;
    }


    //查询用户详细信息
    public ManageUserInfoVo queryManageUsersInfo(String token, Integer userID) {
        UserInfo userInfo = this.userInfoService.queryUserInfoById(Long.valueOf(userID));
        ManageUserInfoVo manageUserInfoVo = new ManageUserInfoVo();
        manageUserInfoVo.setId(userInfo.getUserId().intValue());
        manageUserInfoVo.setNickname(userInfo.getNickName());
        User user = this.userServcie.selectById(userID);
        manageUserInfoVo.setMobile(user.getMobile());
        manageUserInfoVo.setSex(userInfo.getSex()==1?"男":"女");
        manageUserInfoVo.setPersonalSignature("1");
        manageUserInfoVo.setAge(userInfo.getAge());
        manageUserInfoVo.setCountBeLiked(1);//todo
        manageUserInfoVo.setCountLiked(1);//todo
        manageUserInfoVo.setCountMatching(1);//todo
        manageUserInfoVo.setIncome("2000");
        manageUserInfoVo.setOccupation("医生");
        manageUserInfoVo.setUserStatus("1");//todo
        manageUserInfoVo.setCreated(userInfo.getCreated().getTime());
        manageUserInfoVo.setCity(userInfo.getCity());
        manageUserInfoVo.setLastActiveTime(new Date().toString());//todo
        manageUserInfoVo.setLastLoginLocation("中国");//todo
        manageUserInfoVo.setLogo(userInfo.getLogo());
        manageUserInfoVo.setTags("1");
        return manageUserInfoVo;
    }


    //用户冻结
    public boolean freeze(String token, Integer userId,String reasons, String remarks,String freezingTime, String freezingRange) {
        //先判定在redis中该用户是否已经被冻结了
      if (this.redisTemplate.hasKey(FREEZ_KEY_TIME+userId)){
          return false;
      }

        try {
            //如果没有冻结的话
            if (freezingTime.equals("1")){
              this.redisTemplate.opsForValue().set(FREEZ_KEY_TIME+userId,"1", Duration.ofDays(1));
              this.redisTemplate.opsForValue().set(FREEZ_KEY_RANGE+userId,freezingRange,Duration.ofDays(1));
            }
            if (freezingTime.equals("2")){
                this.redisTemplate.opsForValue().set(FREEZ_KEY_TIME+userId,"2", Duration.ofDays(2));
                this.redisTemplate.opsForValue().set(FREEZ_KEY_RANGE+userId,freezingRange,Duration.ofDays(2));
            }
            if (freezingTime.equals("3")){
                this.redisTemplate.opsForValue().set(FREEZ_KEY_TIME+userId,"3", Duration.ofDays(3));
                this.redisTemplate.opsForValue().set(FREEZ_KEY_RANGE+userId,freezingRange,Duration.ofDays(3));
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    //用户解冻
    public boolean unfreeze(String token, Map<String, Object> param) {
        String userId = (String) param.get("userId");
        //先判断用户是否在冻结状态
        if(!this.redisTemplate.hasKey(FREEZ_KEY_TIME+userId)){
            return false;
        }

        try {

            //如果用户还在冻结状态的话,就在redis中删除这些状态
            this.redisTemplate.delete(FREEZ_KEY_TIME+userId);
            this.redisTemplate.delete(FREEZ_KEY_RANGE+userId);
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    //获取pageResult对象
    private PageResult getPageResult(Integer page, Integer pageSize, QueryWrapper queryWrapper){
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPageSize(pageSize);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        //如果查询的结果为空的话,就返回一个默认的pageResult回去
        if (CollectionUtils.isEmpty(userInfoList)) {
            ManageUserInfoVo manageUserInfoVo = new ManageUserInfoVo();
            List<ManageUserInfoVo> manageUserInfoVoList = new ArrayList<>();
            manageUserInfoVoList.add(manageUserInfoVo);
            pageResult.setItems(manageUserInfoVoList);
            pageResult.setCounts(0);
            pageResult.setPages(0);
            return pageResult;
        }
        //进行分页查询
        IPage<UserInfo> userInfoIPage = this.userInfoService.queryByPage(queryWrapper,page,pageSize);
        long pages = userInfoIPage.getPages();
        pageResult.setPages((int)pages);
        List<UserInfo> records = userInfoIPage.getRecords();
        //根据查询到的所有的用户详细信息,获取他们的id集合
        Set<Long> ids = records.stream().map(UserInfo::getUserId).collect(Collectors.toSet());

        //获得user集合
        QueryWrapper<User> queryWrapper1 = new QueryWrapper();
        queryWrapper1.in("id",ids);
        List<User> userList = this.userServcie.selectList(queryWrapper1);

        //获得user的数量
        Integer count = this.userServcie.selectCount(queryWrapper1);

        //建立返回的结果集
        List<ManageUserInfoVo>manageUserInfoVoList = new ArrayList<>();

        //进行循环封装
        for (UserInfo record : records) {
            for (User user : userList) {
                if (user.getId()==record.getUserId()){
                    ManageUserInfoVo manageUserInfoVo = new ManageUserInfoVo();
                    manageUserInfoVo.setId(record.getUserId().intValue());
                    manageUserInfoVo.setLogo(record.getLogo());
                    manageUserInfoVo.setMobile(user.getMobile());
                    manageUserInfoVo.setNickname(record.getNickName());
                    manageUserInfoVo.setSex(record.getSex()==1?"男":"女");
                    manageUserInfoVo.setAge(record.getAge());
                    manageUserInfoVo.setOccupation("医生");
                    manageUserInfoVo.setUserStatus("1");//TODO 用户状态
                    manageUserInfoVo.setLastActiveTime(String.valueOf(new Date()));
                    manageUserInfoVo.setCity(record.getCity());
                    //personalSignature todo
                    //countBeLiked  todo
                    //countLiked  todo
                    //countMatching todo
                    //income todo
                    //created todo
                    //lastLoginLocation todo
                    //tags todo
                    //放进结果集里面
                    manageUserInfoVoList.add(manageUserInfoVo);
                    break;
                }
            }
        }

        pageResult.setCounts(count);

        pageResult.setItems(manageUserInfoVoList);
        return pageResult;
    }
}
